package cn.edu.gzist.chapter03.controller;

import java.io.File;
import java.util.UUID;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("backend")
public class FileController {

    @RequestMapping(value = "fileUpload",method = RequestMethod.POST)
    public String fileUpload(MultipartFile[] files ,  HttpServletRequest request) {
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            String subfix =fileName.substring(fileName.lastIndexOf("."));
            if(!".jpg".equalsIgnoreCase(subfix)){
               return "上传失败，只能上传jpg格式的图片！";
            }
            // 重新生成文件名（根据具体情况生成对应文件名）
            fileName = UUID.randomUUID() + subfix;
            //设置上传的文件所存放的路径
            String dirPath="f:";
            File filePath = new File(dirPath);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            try {
                file.transferTo(new File(filePath.getCanonicalFile() + "/"+fileName));
                return fileName;
            } catch (Exception e) {
                e.printStackTrace();
                // 上传失败，返回失败信息
                return "上传失败！";
            }
        }
        return "上传失败！";
    }
}
